package ensemble.pages

import javafx.scene.control.TreeItem
import javafx.scene.Node
import javafx.scene.layout.Region


abstract class Page(name: String) extends TreeItem[String](name) {
  def path: String =
    if (getParent == null) name
    else {
      val parentPath = getParent.asInstanceOf[Page].path
      if (parentPath.equalsIgnoreCase("ALL")) name
      else parentPath + "/" + name
    }

  def createView: Node = new Region

  def getChild(p: String): Page = {
    def splitBy(src: String, delimit: Char) = {
      val arr = src.split(delimit)
      (arr.head, arr.tail.headOption)
    }

    val (namePart, descendant) = splitBy(p, '/')
    val (childName, anchor) = splitBy(namePart, '#')
    import collection.JavaConverters._
    val child = getChildren.asScala.find(_.getValue == childName).map(_.asInstanceOf[Page])
    child match {
      case Some(docPage: DocPage) =>
        docPage.anchor = anchor.get
        docPage
      case Some(childPage) =>
        descendant.map(childPage.getChild)
        childPage
      case None => null
    }
  }

}

object Page {
  //  implicit def treeItemAsPage(item: TreeItem[Page]) = item.getValue
}

object AllPagesPage extends Page("All")

object Pages {
  val SAMPLES = "SAMPLES"
  val API_DOCS = "API DOCUMENTATION"
  val NEW = "NEW!"
  val HIGHLIGHTS = "HIGHLIGHTS"

  val root = AllPagesPage
  val samples = CategoryPage(SAMPLES)
  val docs = CategoryPage(API_DOCS)
  val newSamples = CategoryPage(NEW)
  val highlightedSamples = CategoryPage(HIGHLIGHTS)
  root.getChildren.addAll(highlightedSamples, newSamples, samples, docs)


  def getPage(path: String) = root.getChild(path)

//  highlightedSamples.getChildren.addAll(List("SAMPLES/Web/Web View",
//    "SAMPLES/Web/H T M L Editor",
//    "SAMPLES/Graphics 3d/Cube",
//    "SAMPLES/Graphics 3d/Cube System",
//    "SAMPLES/Graphics 3d/Xylophone",
//    "SAMPLES/Media/Advanced Media",
//    "SAMPLES/Graphics/Digital Clock",
//    "SAMPLES/Graphics/Display Shelf",
//    "SAMPLES/Charts/Area/Adv Area Audio Chart",
//    "SAMPLES/Charts/Bar/Adv Bar Audio Chart",
//    "SAMPLES/Charts/Line/Advanced Stock Line Chart",
//    "SAMPLES/Charts/Custom/Adv Candle Stick Chart",
//    "SAMPLES/Charts/Scatter/Advanced Scatter Chart").map(path => SamplePage.clone(root.getChild(path).asInstanceOf[SamplePage])): _*)
//
//  newSamples.getChildren.addAll(
//    List("SAMPLES/Canvas/Fireworks",
//      "SAMPLES/Controls/Pagination",
//      "SAMPLES/Controls/Color Picker",
//      "SAMPLES/Controls/List/List View Cell Factory",
//      "SAMPLES/Controls/Table/Table Cell Factory",
//      "SAMPLES/Graphics/Images/Image Operator",
//      "SAMPLES/Scenegraph/Events/Multi Touch").map(path => SamplePage.clone(root.getChild(path).asInstanceOf[SamplePage])): _*)
}
